package com.yihaodian.search.core;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.search.suggest.Lookup.LookupResult;
import org.apache.lucene.search.suggest.analyzing.AnalyzingSuggester;

import com.google.common.collect.Lists;
import com.yihaodian.api.search.SearchException;
import com.yihaodian.api.search.SugRequest;
import com.yihaodian.api.search.SugResponse;
import com.yihaodian.api.search.SugResponse.SugResult;

public class SuggestHandler implements Suggester {

	static Logger log = Logger.getLogger(SuggestHandler.class);

	AnalyzingSuggester suggester = null;

	public SuggestHandler(AnalyzingSuggester suggester) {
		this.suggester = suggester;
	}

	@Override
	public boolean release() throws SearchException {
		return false;
	}

	@Override
	public SugResponse suggest(SugRequest req) {
		String key = req.getKey();
		int number = req.getNumber();
		List<LookupResult> results = suggester.lookup(key, false, number);

		List<SugResult> sugResults = Lists.newArrayList();
		for (LookupResult result : results) {
			SugResult sr = new SugResult();
			sr.key = (String) result.key;
			sr.value = result.value;

			sugResults.add(sr);
		}

		SugResponse resp = new SugResponse();
		resp.setResult(sugResults);
		return resp;
	}

}
